//app.js
// var Promise = require('../../utils/es6-promise.min.js').Promise;
App({
  onLaunch: function() {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    this.setUser()
  },

  getUserInfo: function(cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.getUserInfo({
        withCredentials: false,
        success: function(res) {
          that.globalData.userInfo = res.userInfo
          typeof cb == "function" && cb(that.globalData.userInfo)
        }
      })
    }
  },
  setAccess_token(access_token) {
    this.globalData.access_token = access_token
  },
  setUser(callback){
    let self = this
    let baseUrl = self.globalData.baseUrl,
      header = self.globalData.header
    wx.showLoading({
      title: '正在加载...',
      mask: true
    })
    wx.authorize({
      scope: 'scope.userInfo',
      success(){
        wx.login({
          success: res => {
            if (res.code) {
              let code = res.code
              wx.request({
                url: baseUrl + '/User/login',
                method: 'GET',
                data: { code },
                success: data => {
                  self.setAccess_token(data.data.data.session_key)
                  let access_token = self.globalData.access_token
                  // 设置用户信息
                  let iv, encryptedData
                  wx.getUserInfo({
                    success: uData => {
                      iv = uData.iv
                      encryptedData = uData.encryptedData
                      wx.request({
                        url: baseUrl + '/User/updateUserInfo',
                        method: 'POST',
                        header,
                        data: { access_token, iv, encryptedData },
                        success: data_ => {
                          wx.hideLoading()
                          callback ? callback():''
                        }
                      })
                    }
                  })
                }
              })
            }
          }
        })
      }
    })
  },
  globalData: {
    // baseUrl: 'http://192.168.0.152/wine/index.php/Api/',
    baseUrl: 'https://wine.c-r-bin.top/Api',
    // access_token: 'VvadzGTAEqZLmJzYgWfTzkrKFouSAaavqIWekjWYsHrkiHlIEEDecevKDcARdXLV',
    access_token:'',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }
})
